$(function () {
    $(".search").click(function () {
        submitsearch();
    });
    $("#ckAll").click(function () {
        $("[name='ri_ids[]']").attr("checked", $(this).attr("checked") == "checked" ? true : false);
        putaway(this);
    });
    //<{$lang.submit}><{$lang.put_away}>表单
    $(".submitputaway").click(function () {
        if (chval()) {
            submitputaway();
        }
    });
    //
    //<{$lang.submit}><{$lang.edit}> <{$lang.confirm}><{$lang.put_away}>表单
    $(".submitputawaylist").click(function () {
        if (validate_putaway()) {
            submitEditPutaway();
        }
    });
});
function submitsearch() {
    $("[name=ckAll]").attr("checked", false);
    var receivingCode = $("[name=receivingCode]").val();
    var putawayno = $("[name=putawayNo]").val();
    var qco_code = $("[name=qco_code]").val();
    $('#PutawayloadData').empty();
    $("PutawaylistloadData").empty();
    $("#putaway").hide();
    $("#receiving").hide();
    $("#putawaylist").hide();
    if (receivingCode == '' && putawayno == '' && qco_code=='' ) {
        alertTip('<{$lang.pls_input}><{$lang.search}><{$lang.content}>!');
        return;
    }
    if (putawayno != '') {
        loading();
        PutawaylistloadData(putawayno);
        closeLoading();
        return;
    }
    if (receivingCode != '' || qco_code !='' ) {
        loading();
        ReceivingloadData(receivingCode,qco_code);
        closeLoading();
    }
}
//<{$lang.submit}>后刷新
function refresh() {
    $("[name=ckAll]").attr("checked", false);
    $('#sForm')[0].reset();
    $("#loadData").empty();
    $('#PutawayloadData').empty();
    $("PutawaylistloadData").empty();
    $("#putaway").hide();
    $("#receiving").hide();
    $("#putawaylist").hide();
}
//<{$lang.put_away}>
function submitputaway() {
    $.ajax({
        url:"/product/putaway/submit-putaway/",
        async:false,
        dataType:"json",
        type:"post",
        data:$("#putawayForm").serializeArray(),
        success:function (json) {
            if (json.ask) {
                window.open('/product/putaway/print-putawayno/putawayno/' + json.result.putaway_code, "_blank");
                refresh();
            } else {
                var html = "";
                if (json.result.error != '') {
                    $.each(json.result.error, function (key, val) {
                        html += '<span><img src="/images/no.gif">' + val + '</span>';
                    })
                }
                alertTip(html);
            }
        }
    });
}

//<{$lang.put_away}><{$lang.confirm}>、<{$lang.edit}>
function submitEditPutaway() {
    $.ajax({
        url:"/product/putaway/submit-edit-putaway/",
        async:false,
        dataType:"json",
        type:"post",
        data:$("#putawaylistForm").serializeArray(),
        success:function (json) {
            if (json.ask) {
                $('<div title="<{$lang.tip}>" class="alertTip"><p align="center">' + json.result.msg + '</p></div>').dialog({
                    modal:true,
                    width:450,
                    buttons:{
                        '<{$lang.ok}>':function () {
                            $(this).dialog("close");
                        }
                    }
                });
                //submitsearch();
                refresh();
            } else {
                var html = "";
                if (json.result.error != '') {
                    $.each(json.result.error, function (key, val) {
                        html += '<span><img src="/images/no.gif">' + val + '</span>';
                    })
                }
                alertTip(html);
            }
        }
    });
}
//查看<{$lang.inventory}>
function inventory(pid) {
    $.ajax({
        url:"/product/putaway/inventory/",
        async:false,
        dataType:"json",
        type:"post",
        data:{'product_id':pid},
        success:function (json) {
            if (json == undefined)return;
            var html = "";
            if (json.ask) {
                $.each(json.result, function (k, v) {
                    html += "<tr>";
                    html += "<td>"+v.customer_id+'-'+ v.product_sku + "</td>";
                    html += "<td>" + v.ws_code + "</td>";
                    html += "<td>" + v.wsc_code + "</td>";
                    html += "<td>" + v.wp_quantity + "</td>";
                    html += "</tr>";
                });
                $("#wplistloadData").html(html);
                $("#wplistloadData>tr:even").addClass("even-tr");
                $("#dialog").dialog({title:'<{$lang.product}><{$lang.detail}>', autoOpen:true, width:400, modal:false,
                    show:"slide",
                    resizable:false, 'buttons':{'close':function () {
                        $(this).dialog('close');
                    }}});
            } else {
                if (json.result.error != '') {
                    $.each(json.result.error, function (key, val) {
                        html += '<span><img src="/images/no.gif">' + val + '</span>';
                    })
                }
                alertTip(html);
            }
        }
    });
}
//<{$lang.search}>ReceivingNo
function ReceivingloadData(code,qco_code) {
    $("#receiving").show();
    $.ajax({
        url:"/product/putaway/receiving-list/",
        async:false,
        dataType:"json",
        type:"post",
        data:{"receivingCode":code,"qco_code":qco_code},
        success:function (json) {
            var html = "";
            if (json.ask) {
                var i = 0;
                $.each(json.result, function (k, v) {
                    var order_type = v.order_type == 1 ? '<{$lang.standard}>' : '<{$lang.return}>';
                    var is_qc = (v.is_qc==1) ? '<{$lang.yes}>' :'<{$lang.no}>';
                    html += '<tr><td><input onclick="putaway(this);" type="checkbox" app="' + v.wait_putaway_total + '" value="' + v.ri_id + '" name="ri_ids[]"/></td>';
                    html += '<td>' + v.receiving_code + '</td><td>' + v.line_no + '</td>';
                    html += '<td>'+v.customer_id +'-'+ v.product_sku + '</td><td>' + v.product_title + '</td><td>' + v.weight + '</td><td>' + order_type + '</td>';
                    html += '<td>' + v.order_qty + '</td><td>' + v.received_qty + '</td>';
                    html += '<td>' + v.putaway_qty + '</td><td><a href="javascript:inventory(' + v.product_id + ');"><img src="/images/icon/info.jpg" title="<{$lang.detail}>"></a></td></tr>';
                });
                $("#loadData").html(html);
            } else {
                var error=(json.error!=undefined)?json.error:'<{$lang.no_data}>';
                $("#putaway").hide();
                $("#loadData").html("<tr><td colspan='13' align='center'>"+error+"</td></tr>");
            }
        }
    });
}

function PutawayloadDatalist(r_id) {
    if (r_id == '') {
        return;
    }
    loading();
    $("#putaway").show();
    $.ajax({
        url:"/product/putaway/putaway-info/",
        async:false,
        dataType:"json",
        type:"post",
        data:{"ri_id":r_id},
        success:function (json) {
            closeLoading();
            var html = "";
            var putaway_lot_number = 1;
            if (json.ask) {
                //input<{$lang.data}>不能<{$lang.delete}>
                $.each(json.result,function(k,v){
                var phtml='';
                if(v.putaway_ids!='0'){
                    phtml="<input value='" + v.putaway_ids + "' type ='hidden' name='putaway_ids[]'>";
                }
                var default_ws_code = (v.default_ws_code != '' && v.default_ws_code != null) ? v.default_ws_code : '';
                html += "<tr name='tr_ri_id_" + r_id + "' class='even-tr'>";
                html += "<td><input value='" + putaway_lot_number + "' type ='hidden' name='lot[]' id='putaway_lot_number_" + v.product_id + "'><span>" + putaway_lot_number + "</span></td>";
                html += "<td><input value='" + v.receiving_code + "' type ='hidden' name='receiving_code[]' id='receiving_code_" + v.product_id + "'>" + v.receiving_code + "</td>";
                html += "<td id='line_no_" + v.product_id + "'>" + v.line_no + "</td>";
                html += "<td>" +phtml+ v.category + "</td>";
                html += "<td><input value='" + v.product_sku + "' type ='hidden' name='product_sku[]'><input value='" + v.product_id + "' type ='hidden' name='product_id[]'>" +v.customer_id+'-'+ v.product_sku + "</td>";
                html += '<td><input type="hidden" name="received_total[]" value="' +v.received_qty + '"/><input type="hidden" name="received_qty_total[]" value="' + v.wait_putaway_total + '" id="received_qty_total_' + v.product_id + '"/><input type="text" class="inputText" name="received_qty[]" onblur="calqty(this)"  style="width:80px;text-align:right" value="' + v.wait_putaway_total + '" /></td>';
                html += "<td><input value='" + default_ws_code + "' id='default_ws_code_" + v.product_id + "' type ='hidden' name='default_ws_code[]'>" + default_ws_code + "</td>";
                html += "<td><input value='" + default_ws_code + "' type ='type' name='ws_code[]' style='width:80px;text-align:right'>&nbsp;<a href=\"javascript:void(0);\" onclick=\"selectshelf(this,"+v.product_id+");\"><img src=\"/images/icon/support.png\" alt=\"<{$lang.pls}><{$lang.ws_code}>\"></a></td>";
                html += "<td><a href=\"javascript:void(0);\" onclick=\"addshelf(this,'" + r_id + "');\"><img src=\"/images/icon/plus_sign.gif\" alt=\"<{$lang.add}>\"></a></td>";
                html += "</tr>";
                });
                $("#PutawayloadData").append(html);
                //$("#PutawayloadData>tr:even").addClass("even-tr");
            } else {
                var message='<{$lang.no_data}>';
                if(json.message){message=json.message;}
                $("#PutawayloadData").append("<tr name='tr_ri_id_" + r_id + "' class='even-tr'><td colspan='10' align='center'>"+message+"</td></tr>");
            }
        }
    });
}

function addshelf(obj, r_id) {
    var html = $(obj).parent().parent().html();
    var num = $("#PutawayloadData>tr").length;
    $(obj).parent("td").parent("tr").after('<tr name="tr_ri_id_' + r_id + '" class="add_' + num + '">' + html + '</tr>');
    var objtr = $(".add_" + num + ">td");
    loading();
    objtr.find("[name='ws_code[]']").val('');
    objtr.eq(0).html('<input type="hidden" class="inputText" name="lot[]"  style="width:80px;text-align:right" value="0"/><span></span>');
    objtr.eq(5).html('<input type="text" class="inputText" name="received_qty[]"  style="width:80px;text-align:right" value="0" onblur="calqty(this);"/>');
    //objtr.eq(8).html("<a href=\"javascript:void(0);\" onclick=\"delshelf(this);\"><img src=\"/images/icon/minus_sign.gif\" alt=\"<{$lang.delete}>\"></a>");
    objtr.last().html("<a href=\"javascript:void(0);\" onclick=\"delshelf(this);\"><img src=\"/images/icon/minus_sign.gif\" alt=\"<{$lang.delete}>\"></a>");
    putaway_lot_number(0);
    closeLoading();
}
function delshelf(obj) {
    $(obj).parent('td').parent('tr').remove();
    putaway_lot_number(0);
}

function putaway(obj) {
//每次重新<{$lang.search}>，如已存则不处理，否则<{$lang.add}>
    $("#loadData [name='ri_ids[]']").each(function (k, v) {
        var ri_id = $(this).val();
        var trname = $('[name=tr_ri_id_' + ri_id + ']');
        if ($(this).is(":checked") && $(this).attr("app") > 0) {
            if (!trname.length > 0) {
                PutawayloadDatalist(ri_id);
            }
        } else {
            if (trname.length > 0) {
                //<{$lang.delete}>
                trname.each(function (tk, tv) {
                    $(this).remove();
                })
            }
            $(this).attr("checked", false);
        }
    })
    if ($('#PutawayloadData').children().length <= 0) {
        $("[name=ckAll]").attr("checked", false);
        $("#putaway").hide();
    }
    putaway_lot_number(0);
}
function putaway_lot_number(val) {
    $("#PutawayloadData [name='lot[]']").each(function (k, v) {
        var v = 0;
        v = val + k + 1;
        $(this).val(v);
        $(this).parent().children("span").html(v);
    });
}

function chval() {
    var errmsg = "";
    var pattern = /^\d+$/;//匹配正整数
    $("[name='received_qty[]']").each(function (k, v) {
        var this_val = $(this).val();
        if (this_val == '' || this_val == '0' || !pattern.test(this_val)) {
            errmsg += '<span><img src=\"/images/no.gif\"> ' + (k + 1) + ' ,<{$lang.put_away}><{$lang.quantity}><{$lang.illegal}>!</span>';
        }
    });
    $("[name='ws_code[]']").each(function (k, v) {
        var ws_this_val = $(this).val();
        if (ws_this_val == '') {
            errmsg += '<span><img src=\"/images/no.gif\"> ' + (k + 1) + ' ,<{$lang.ws_code}><{$lang.illegal}>!</span>';
        }
    });
    if (errmsg != '') {
        alertTip(errmsg);
        return false;
    }
    errmsg = updatetotal(1);
    if (errmsg != ''&& errmsg!=true) {
        putawayTip(errmsg);
        return false;
    }
    return true;
}
//function updatetotal(type) {return true}
function updatetotal(type) {
    var err = 0;
    var msg = "";
    if (type == '') {
        type = 0
    }
    ;
    $("#loadData [name='ri_ids[]']:checked").each(function (k, v) {
        var ri_id = $(this).val();
        var obj = $('[name=tr_ri_id_' + ri_id + ']');
        var total = obj.find("[name='received_qty_total[]']").val();//<{$lang.product}>总<{$lang.put_away}><{$lang.quantity}>
        var addtotal = 0;//填写的<{$lang.put_away}><{$lang.quantity}>
        var productid = obj.find("td").eq(4).html();
        obj.find("[name='received_qty[]']").each(function (rk, rv) {
                addtotal += $(this).val() * 1;
            }
        );
        if (addtotal * 1 > total * 1) {
            err += 1;
        }
        if (addtotal * 1 < total * 1) {
            msg += "<span><{$lang.product}><{$lang.sku}>:" + productid + " <{$lang.for_put_away}><{$lang.quantity}>:" + total + ",<{$this.time}><{$lang.put_away}><{$lang.quantity}>:" + addtotal + " </span>";
        }
    });
    if (err > 0) {
        return false;
    }
    if (msg != '' && type == 1) {
        msg += "<span><{$lang.ok}><{$lang.operation}>？</span>";
        return msg;
    }
    return true;
}
function calqty(obj) {
    var this_val = $(obj).val();
    var pattern = /^\d+$/;//匹配正整数
    if (!pattern.test(this_val)) {
        alertTip("<{$lang.pls_input}><{$lang.legal}><{$lang.quantity}>!");
        $(obj).val(0);
        return;
    }
    if (!updatetotal(0)) {
        alertTip("<{$lang.set}><{$lang.put_away}><{$lang.total}><{$lang.quantity}><{$lang.can_not_more_than}><{$lang.no_put_away}><{$lang.quantity}>!");
        $(obj).val(0);
    }
}

//<{$lang.confirm}><{$lang.put_away}> begin
function PutawaylistloadData(code) {
    if (code == '') {
        return;
    }
    $("#putawaylist").show();
    $.ajax({
        url:"/product/putaway/putaway-list/",
        async:false,
        dataType:"json",
        type:"post",
        data:{"putawayno":code},
        success:function (json) {
            var html = "";
            if (json.ask) {
                var i = 0;
                var submit = false;
                $.each(json.result, function (k, v) {
                    var default_ws_code = (v.default_ws_code != '' && v.default_ws_code != null) ? v.default_ws_code : '';
                    if (k == 0) {
                        submit = (v.putaway_status == '1') ? true : false;
                    }
                    html += "<tr class='even-tr' name='oldputaway'>"
                    html += '<td><input type="hidden" name="putaway_id[]" class="' + v.product_sku + '" value=' + v.putaway_id + '><input type="hidden" name="putaway_lot_number[]" value=' + v.putaway_lot_number + '>' + v.putaway_lot_number + '</td><td>' + v.receiving_code + '</td><td>' + v.category + '</td><td>'+v.customer_id+'-'+ v.product_sku + '</td>';
                    html += '<td><input type="hidden" name="product_sku[]" value=' + v.product_sku + '><input type="hidden" name="product_id[]" value=' + v.product_id + '><input type="hidden" name="py_ids[]" value=' + v.putaway_id + '>' + v.putaway_status_text + '</td>';
                    html += '<td><input type="hidden" name="putaway_qty_total[]" id="putaway_qty_total_' + v.putaway_id + '" value=' + v.putaway_quantity + '><input type="text" class="inputText" id="putaway_quantity_' + v.putaway_id + '" name="putaway_quantity[]" onblur="qty(this)"  style="width:80px;text-align:right" value="' + v.putaway_quantity + '" /></td>';
                    html += "<td>" + default_ws_code + "</td>";
                    html += "<td><input value='" + v.ws_code + "' type ='type' name='putaway_ws_code[]' style='width:80px;text-align:right'>&nbsp;<a href=\"javascript:void(0);\" onclick=\"selectshelf(this,"+v.product_id+");\"><img src=\"/images/icon/support.png\" alt=\"<{$lang.pls}><{$lang.ws_code}>\"></a></td>";
                    html += "<td><a href=\"javascript:void(0);\" onclick=\"addputaway(this,'" + v.putaway_id + "');\"><img src=\"/images/icon/plus_sign.gif\" alt=\"<{$lang.add}>\"></a></td>";
                    html += "</tr>"
                });
                if (submit) {
                    $("#submitputawayid").hide();
                }else{
                    $("#submitputawayid").show();
                }
                $("#PutawaylistloadData").html(html);
            } else {
                $("#submitputawayid").hide();
                $("#PutawaylistloadData").html("<tr><td colspan='9' align='center'><{$lang.no_data}></td></tr>");
            }
        }
    });
}

function addputaway(obj, pid) {
    var html = $(obj).parent().parent().html();
    var num = $("#PutawaylistloadData>tr").length;
    num += 1;
    loading();
    $(obj).parent("td").parent("tr").after('<tr name="addputaway" class="addputaway_' + num + '">' + html + '</tr>');
    var objtr = $(".addputaway_" + num + ">td");
    objtr.find("[name='putaway_ws_code[]']").val('');
    objtr.eq(0).html('<input type="hidden" name="p_id[]" value=' + pid + '><input type="hidden" name="putaway_lot_number[]" value=' + num + '><span>' + num + '</span>');
    objtr.eq(5).html('<input type="text" app="pd_' + pid + '" class="inputText" name="putaway_quantity[]"  style="width:80px;text-align:right" value="0" onblur="qty(this);"/>');
    objtr.eq(8).html("<a href=\"javascript:void(0);\" onclick=\"delputaway(this);\"><img src=\"/images/icon/minus_sign.gif\" alt=\"<{$lang.delete}>\"></a>");
    update_lot_number();
    closeLoading();
}

function delputaway(obj) {
    $(obj).parent('td').parent('tr').remove();
    update_lot_number();
    updateputawaytotal(0);
}

function update_lot_number() {
    var p = $("[name=oldputaway]", "#PutawaylistloadData").length;
    $("[name=addputaway] [name='putaway_lot_number[]']").each(function (k, v) {
        if ($(this).val() * 1 > p * 1) {
            var v = 0;
            v = p + k + 1;
            $(this).val(v);
            $(this).parent().children("span").html(v);
        }
    });
}

function qty(obj) {
    var this_val = $(obj).val();
    var pattern = /^\d+$/;//匹配正整数
    if (!pattern.test(this_val)) {
        alertTip("<{$lang.pls_input}><{$lang.legal}><{$lang.quantity}>!");
        $(obj).val(0);
        updateputawaytotal(0);
        return;
    }
    var msg = updateputawaytotal(0);
    if (msg != '' && msg != undefined && msg!=true) {
        alertTip(msg);
        $(obj).val(0);
        updateputawaytotal(0);
        return;
    }
}
//<{$lang.put_away}><{$lang.quantity}>验证
function updateputawaytotal(type) {
    var errmsg = '';
    $("[name='putaway_id[]']", "#PutawaylistloadData").each(function (k, v) {
        var productid = $(this).val();
        var product<{$lang.sku}> = $(this).attr('class');
        var total = $("#putaway_qty_total_" + productid).val() * 1;
        var defaulttotal = $("#putaway_quantity_" + productid).val() * 1;
        var addtotal = 0;
        $("[name=addputaway] [name='putaway_quantity[]']", "#PutawaylistloadData").each(function (k, v) {
            if ($(this).attr('app') == 'pd_' + productid)
                addtotal += $(this).val() * 1;
        });
        //addtotal+=defaulttotal;
        if (addtotal > total) {
            errmsg += "<span><{$lang.product}><{$lang.sku}>：" + product<{$lang.sku}> + " <{$lang.put_away}><{$lang.quantity}>：" + (addtotal + defaulttotal) + " <{$lang.more_than}><{$lang.put_away}><{$lang.total}><{$lang.quantity}>：" + total + "</span>";
        } else {
            $("#putaway_quantity_" + productid).val(total - addtotal);
        }
    });
    if (errmsg != '') {
        return errmsg;
    }
}

function validate_putaway() {
    var errmsg = "";
    var pattern = /^\d+$/;//匹配正整数
    $("[name='putaway_quantity[]']", "#PutawaylistloadData").each(function (k, v) {
        var this_val = $(this).val();
        if (this_val == '' || this_val == '0' || !pattern.test(this_val)) {
            errmsg += '<span><img src=\"/images/no.gif\">LotID: ' + $("#PutawaylistloadData > tr").eq(k).find("td").eq(0).last().text() + ' ,<{$lang.put_away}><{$lang.quantity}><{$lang.illegal}>!</span>';
        }
    });
    $("[name='putaway_ws_code[]']", "#PutawaylistloadData").each(function (k, v) {
        var ws_this_val = $(this).val();
        if (ws_this_val == '') {
            errmsg += '<span><img src=\"/images/no.gif\">LotID: ' + $("#PutawaylistloadData > tr").eq(k).find("td").eq(0).last().text() + ',<{$lang.ws_code}><{$lang.illegal}>!</span>';
        }
    });
    if (errmsg != '') {
        alertTip(errmsg);
        return false;
    }
    errmsg = updateputawaytotal(0);
    if (errmsg != '' && errmsg != undefined) {
        alertTip(errmsg);
        return false;
    }
    return true;
}
//<{$lang.edit}><{$lang.put_away}> end

//<{$lang.operation}><{$lang.tip}>
function alertTip(tip) {
    $('<div title="<{$lang.tip}>" class="alertTip"><p align="center">' + tip + '</p></div>').dialog({
        modal:true,
        width:450,
        buttons:{
            '<{$lang.ok}>':function () {
                $(this).dialog("close");
            }
        }
    });
}
//<{$lang.put_away}><{$lang.quantity}><{$lang.tip}>
function putawayTip(tip) {
    $('<div title="<{$lang.tip}>" class="alertTip"><p align="center">' + tip + '</p></div>').dialog({
        modal:true,
        width:450,
        buttons:{
            '<{$lang.ok}>':function () {
                submitputaway();
                $(this).dialog("close");
            },
            '<{$lang.cancel}>':function () {
                $(this).dialog("close");
            }
        }
    });
}